package edu.uc.labs.MobilePrinting.Fetch;

import edu.uc.labs.MobilePrinting.Configurator;
import java.io.*;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
import org.apache.log4j.Logger;

/**
 *
 * This class sends data to the Server and
 * receives an XML formated list of Printers
 * @param server the IPAddress or DNS name of the server
 * @param ipAddress the IPAddress to send to the server
 */
public class XMLFetcher {

    private String input = "";
    private String resource = "/mobileprint.pl?ip=";
    private String os = "&os=";
    private String url, server, ip ;
    private URL u;
    private URLConnection conn;
    private Configurator conf = new Configurator();
    private Logger logger = conf.getLogger();


    public XMLFetcher(String iServer, String iAddress, String osName) throws MalformedURLException, IOException {        
        server = iServer;
        ip = iAddress;
        os += osName;
        connect();
    }

    public String getResponse() {
        return input;
    }

    public boolean isConnected() {     
        return true;
    }

    public void connect() throws IOException, ConnectException {
        buildURL();
        logger.debug("The URL to send: " + u.toString());
        conn = u.openConnection();
        InputStream instream = conn.getInputStream();
        Scanner in = new Scanner(instream);

        while (in.hasNextLine()) {
            input += in.nextLine() + "\n";
        }


    }

    public void buildURL() throws MalformedURLException {
        // Build the URL
        url = "http://" + server + resource + ip + os;
        u = new URL(url);
    }

    public void setIP(String newIP){
        ip = newIP;
    }

}
